class MyPromise{
    constructor(handle) {
        this['status'] = "pedding";
        this['PromiseResult'] = undefined;
        
        handle(this._resolve.bind(this),this._reject.bind(this));
    }
    _resolve(arg){
        // console.log(this);
        this['status'] = "fufilled";
        this['PromiseResult'] = arg;
    }
    _reject(arg){
        this['status'] = "rejected";
        this['PromiseResult'] = arg;
    }
    then(onResolved,onRejected){
        console.log("then");
        onResolved && onResolved(this.PromiseResult);
        // then的链式操作 实现 1.返还this 2.返还实例化对象；
        return this;
    }
}

function myProAll(arr){
    return new Promise(resolve=>{
        let count = 0 ; 
        let newArr = [] ;
        arr.forEach(item=>{
            item.then(res=>{
                newArr.push(res);
                count ++ ;
                if( count == arr.length ){
                    resolve(newArr);
                }
            })
        });
    });
}

function myAllSettled(arr){
    return new Promise(resolve=>{
        let count = 0 ; 
        let newArr = new Array(arr.length);
        arr.forEach(item=>{
            item.then(res=>{
                let obj = {} ;
                obj['PromiseState'] = "fulfilled";
                obj['PromiseResult'] = res;
                newArr[count] = obj ;
                count ++ ;
                if( count == arr.length ){
                    resolve(newArr);
                }
            },rej=>{
                let obj = {} ;
                obj['PromiseState'] = "rejected";
                obj['reason'] = rej ;
                newArr[count] = obj ;
                count ++ ;
                if( count == arr.length ){
                    resolve(newArr);
                }
            });
        });
    });
}   

